package com.finger.forest.utils;

import android.content.Context;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Handler;
import android.util.Log;

import com.finger.forest.PatrolReportActivity;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Random;

public class AudioRecoderUtils{

    private final String TAG = "AudioRecoderUtils";

    public static final int MAX_LENGTH = 1000 * 60 * 10;// 最大录音时长1000*60*10;
    public double volume = 0;

    private OnAudioStatusUpdateListener audioStatusUpdateListener;
    private Context context;

    private long startTime;
    private long endTime;

    private final Handler mHandler = new Handler();
    private Runnable mUpdateMicStatusTimer = new Runnable() {
        public void run() {
            updateMicStatus();
        }
    };

    private int SPACE = 100;// 间隔取样时间
    private boolean isRecording = false;

    public AudioRecoderUtils(Context context){
        this.context = context;
    }

    /**
     * 开始录音
     * @return
     */
    public void startRecord() {
        updateMicStatus();
        startTime = System.currentTimeMillis();
        Log.i(TAG, "startTime" + startTime);
    }

    /**
     * 停止录音
     */
    public long stopRecord() {
        endTime = System.currentTimeMillis();
        isRecording = false;
        mHandler.removeCallbacks(mUpdateMicStatusTimer);
        audioStatusUpdateListener.onStop("");
        return endTime - startTime;
    }

    public void setOnAudioStatusUpdateListener(OnAudioStatusUpdateListener audioStatusUpdateListener) {
        this.audioStatusUpdateListener = audioStatusUpdateListener;
    }

    /**
     * 更新麦克状态
     */
    private void updateMicStatus() {
        /*double d = Math.random()*100;
        double db = new Random().nextInt(100);*/
        audioStatusUpdateListener.onUpdate(volume,System.currentTimeMillis()-startTime);
        mHandler.postDelayed(mUpdateMicStatusTimer, SPACE);

        //开启一个线程获取分贝
        new Thread(new Runnable() {
            @Override
            public void run() {
                updateVolume();
            }
        }).start();

    }

    private void updateVolume(){
        Log.i(TAG, "开始录音");
        //16K采集率
        int frequency = 16000;
        //格式
        int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
        //16Bit
        int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;

        try {
            int bufferSize = AudioRecord.getMinBufferSize(frequency, channelConfiguration, audioEncoding);
            AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, frequency, channelConfiguration, audioEncoding, bufferSize);

            short[] buffer = new short[bufferSize];
            //开始录制音频
            try {
                // 防止某些手机崩溃，例如联想
                audioRecord.startRecording();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
            Log.i(TAG, "开始录音");
            isRecording = true;
            while (isRecording) {
                int bufferReadResult = audioRecord.read(buffer, 0, bufferSize);
                long v = 0;
                for (int i = 0; i < bufferReadResult; i++) {
                    v += buffer[i] * buffer[i];
                }
                // 平方和除以数据总长度，得到音量大小。
                double mean = v / (double) bufferReadResult;
                volume = 10 * Math.log10(mean);
                Log.d(TAG, "分贝值:" + volume);
            }
            //停止录制
            try {
                // 防止某些手机崩溃，例如联想
                audioRecord.stop();
                // 彻底释放资源
                audioRecord.release();
                audioRecord = null;
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
        } catch (Throwable t) {
            Log.e(TAG, "录音失败");
            t.printStackTrace();
        }
    }

    public interface OnAudioStatusUpdateListener {
        /**
         * 录音中...
         * @param db 当前声音分贝
         * @param time 录音时长
         */
        public void onUpdate(double db, long time);

        /**
         * 停止录音
         * @param filePath 保存路径
         */
        public void onStop(String filePath);

    }

}


